package com.cyzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.cyzy.dto.AdoptDetailDto;
import com.cyzy.dto.AdoptListDto;
import com.cyzy.mapper.AdoptMapper;
import com.cyzy.mapper.OrderMapper;
import com.cyzy.mapper.ProtocolMapper;
import com.cyzy.pojo.Adopt;
import com.cyzy.pojo.Orders;
import com.cyzy.pojo.Protocol;
import com.cyzy.service.AdoptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 认养服务实现类
 */
@Service
public class AdoptServiceImpl extends MPJBaseServiceImpl<AdoptMapper, Adopt> implements AdoptService {

    @Autowired
    private ProtocolMapper protocolMapper;
    
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public List<AdoptListDto> getAdoptList() {
        // 查询状态为正常的认养信息
        List<Adopt> adoptList = this.list(new LambdaQueryWrapper<Adopt>()
                .eq(Adopt::getAdoptStatus, 1)
                .orderByAsc(Adopt::getAdoptId));
        
        List<AdoptListDto> resultList = new ArrayList<>();
        
        for (Adopt adopt : adoptList) {
            // 统计已售数量（所有订单中order_quantity的总和）
            QueryWrapper<Orders> orderQuery = new QueryWrapper<>();
            orderQuery.select("IFNULL(SUM(order_quantity), 0) as total_sold")
                     .eq("related_id", adopt.getAdoptId())
                     .eq("order_type", "认养")
                     .in("order_status", 1, 2);
            
            List<Map<String, Object>> result = orderMapper.selectMaps(orderQuery);
            Integer soldCount = 0;
            if (!result.isEmpty() && result.get(0).get("total_sold") != null) {
                soldCount = Integer.valueOf(result.get(0).get("total_sold").toString());
            }
            
            // 封装DTO
            AdoptListDto dto = new AdoptListDto();
            dto.setId(adopt.getAdoptId());
            dto.setTitle(adopt.getAdoptName());
            dto.setSubtitle(adopt.getAdoptProduct());
            dto.setSold(soldCount);
            dto.setRemain((int) adopt.getAdoptStock() - soldCount);
            dto.setPrice(BigDecimal.valueOf(adopt.getAdoptPrice()).toString());
            dto.setImage(adopt.getAdoptImage());
            
            resultList.add(dto);
        }
        
        return resultList;
    }

    @Override
    public Protocol getAdoptProtocol() {
        // 查询协议名称为"认养协议"且状态为正常的协议
        return protocolMapper.selectOne(new LambdaQueryWrapper<Protocol>()
                .eq(Protocol::getProtocolName, "认养协议")
                .eq(Protocol::getProtocolStatus, 1));
    }

    @Override
    public AdoptDetailDto getAdoptDetail(Long adoptId) {
        // 根据ID查询认养信息
        Adopt adopt = this.getOne(new LambdaQueryWrapper<Adopt>()
                .eq(Adopt::getAdoptId, adoptId)
                .eq(Adopt::getAdoptStatus, 1));
        
        if (adopt == null) {
            return null;
        }
        
        // 统计已售数量（所有订单中order_quantity的总和）
        QueryWrapper<Orders> orderQuery = new QueryWrapper<>();
        orderQuery.select("IFNULL(SUM(order_quantity), 0) as total_sold")
                 .eq("related_id", adoptId)
                 .eq("order_type", "认养")
                 .in("order_status", 1, 2);
        
        List<Map<String, Object>> result = orderMapper.selectMaps(orderQuery);
        Integer soldCount = 0;
        if (!result.isEmpty() && result.get(0).get("total_sold") != null) {
            soldCount = Integer.valueOf(result.get(0).get("total_sold").toString());
        }
        
        // 计算实际可用库存
        int availableStock = (int) adopt.getAdoptStock() - soldCount;
        
        // 封装DTO
        AdoptDetailDto dto = new AdoptDetailDto();
        dto.setId(adopt.getAdoptId());
        dto.setTitle(adopt.getAdoptName());
        dto.setSubtitle(adopt.getAdoptInfo());
        dto.setPrice(BigDecimal.valueOf(adopt.getAdoptPrice()).toString());
        dto.setImage(adopt.getAdoptImage());
        dto.setVideo(adopt.getAdoptAudio());
        dto.setProductType(adopt.getAdoptProduct());
        
        // 拼接实际可用库存数量和单位
        String totalArea = availableStock + (adopt.getAdoptUnit() != null ? adopt.getAdoptUnit() : "");
        dto.setTotalArea(totalArea);
        
        // 拼接周期和"天"
        dto.setPeriod(adopt.getAdoptCycle() + "天");
        
        dto.setAdoptType(adopt.getAdoptType());
        
        // 格式化截止时间
        if (adopt.getAdoptEndtime() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dto.setDeadline(sdf.format(adopt.getAdoptEndtime()));
        }
        
        dto.setDescription(adopt.getAdoptInfo());
        
        return dto;
    }
} 